package com.ruoyi.health.report.utils;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.IOException;

public class Base64ToMultipartFile {
    public static MultipartFile base64Convert(String base64) {
        // 检查输入是否为空
        if (base64 == null || base64.isEmpty()) {
            return null;
        }

        String[] baseStrs = base64.split(",");

        // 检查分割后的数组是否有足够的元素
        if (baseStrs.length < 2) {
            // 如果没有逗号分隔的格式，则认为整个字符串就是base64数据
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            try {
                b = decoder.decodeBuffer(base64);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 使用默认的MIME类型
            return new Base64DecodeMultipartFile(b, "data:image/png;base64");
        } else {
            // 正常的base64格式，包含data:image/...;base64,前缀
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = new byte[0];
            try {
                b = decoder.decodeBuffer(baseStrs[1]);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new Base64DecodeMultipartFile(b, baseStrs[0]);
        }
    }
}
